package trilium

import (
	"context"
	"encoding/json"
	"gitee.com/Luna-CY/hui-hui/internal/interface/application"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/internal/runtime"
	"github.com/hashicorp/go-version"
	"os"
	"path/filepath"
)

func (cls *Trilium) CheckLocationState(_ context.Context) error {
	logger.GetLogger().Sugar().Info("检测Trilium服务本地状态")
	_, err := os.Stat(filepath.Join(rootPath, "package.json"))
	if nil != err && !os.IsNotExist(err) {
		return err
	}

	// 不存在=未安装
	if os.IsNotExist(err) {
		cls.UpdateState(application.NotInstall, 0, "")

		return nil
	}

	pf, err := os.Open(filepath.Join(rootPath, "package.json"))
	if nil != err {
		return err
	}

	defer func() {
		_ = pf.Close()
	}()

	// 解析版本号
	var content struct {
		Version string `json:"version"`
	}

	if err := json.NewDecoder(pf).Decode(&content); nil != err {
		return err
	}

	min, err := version.NewVersion(runtime.TriliumMinimumVersion)
	if nil != err {
		return err
	}

	tv, err := version.NewVersion(content.Version)
	if nil != err {
		return err
	}

	// 如果大于或等于最小版本号则返回
	if tv.GreaterThanOrEqual(min) {
		cls.UpdateState(application.Installed, 0, "")

		return nil
	}

	cls.UpdateState(application.VersionNotEffect, 0, "")

	return nil
}
